﻿using CRMExam.Database;
using CRMExam.Helpers;
using CRMExam.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using System.Net.Mail;
using System.Net;
using System.Configuration;

namespace CRMExam.Controllers
{
    [Authorize(Roles = "Admin")]
    public class AdministratorController : Controller
    {

        public ActionResult Admin()
        {
            var model = new AdministratorViewModels();

            return View(model);
        }

        [HttpPost]
        public ActionResult Admin(AdministratorViewModels model)
        {
            Guid guid = Guid.NewGuid();
            var currentUser = User.Identity.GetUserId();

            

            string logo = "";

            //string link = "http://localhost:65505/InviteUser/Invite/" + guid.ToString();
            string link = ConfigurationManager.AppSettings["HostServer"] + "/InviteUser/Invite/" + guid.ToString();

            using (CRMExam1Entities context = new CRMExam1Entities())
            {
                var user = context.AspNetUsers.FirstOrDefault(u=> u.Id == currentUser);
                logo = ((context.AspNetUsers.FirstOrDefault(u => u.Id == currentUser)).Customer).PictureLogoUrl;
                context.InvitedUsers.Add(new InvitedUser { Id = guid, CustomerId = user.CustomerId });
                context.SaveChanges();
            }

            string body = "<div style='margin:20px'></br><img src="
                + logo
                + " width='100px'/></br></br><h2>WELCOME AS A CRM USER AT VOLVO</h2></br><p>Please use the link below...</p>"
                + "<a href=" + link + ">Volvo CRM</a></div>";

            var message = new MailMessage("vladimirthecrazycat@gmail.com", model.Email, "We welcome you to register as a new user", body);

            message.IsBodyHtml = true;

            Mail.SendMail(message);

            return RedirectToAction("Admin");
        }
    }
}